<?php
/**
 * Created by PhpStorm.
 * User: zhaojunlike
 * Date: 2016/12/1
 * Time: 14:22
 */

namespace Home\Controller;


use Common\Helper\OrderHelper;

class ProjectController extends AuthController
{

    protected function _initialize()
    {
        parent::_initialize();
        //实名认证
        $this->checkUserRealAuth();
    }

    public function my_project()
    {
        //查询一遍
        $map = array();
        $map['jg_id'] = $this->user['u_id'];
        $logs = M('jon_game_logs')
            ->where($map)
            ->order('time DESC')
            ->select();
        $uids = array();
        $uids[] = 0;
        foreach ($logs as $k => $v) {
            $uids[] = $v['user_id'];//加入查询集合
        }
        $myLetUsers = M('jon_game_logs')
            ->join('LEFT JOIN user ON user.u_id=jon_game_logs.user_id')
            ->join('LEFT JOIN game ON game.g_id=jon_game_logs.game_id')
            ->join('LEFT JOIN jon_game ON jon_game.j_id=jon_game_logs.jon_id')
            ->where(array('user.u_id' => array('in', $uids)))
            ->field('user.u_name,user.u_id,jon_game.back_no,jon_game.order_no,jon_game.j_id,jon_game.create_time as g_create_time,jon_game.end_grade,game.g_name,game.g_start,game.g_short,jon_game.j_id,jon_game.pay_status')
            ->order('jon_game.create_time DESC')
            ->select();
        $this->assign('_list', $myLetUsers);
        $this->display();
    }

    public function index()
    {
        $this->display();
    }


    /**
     * 报名
     */
    public function apply()
    {
        $id = I('id');
        $game = M('game')->where(array('g_id' => $id))->find();
        if (!$game) {
            $this->error('比赛不存在');
        }
        $allGame = M('all_game')->where(array('all_id' => $game['all_id']))->find();
        if (!$allGame) {
            $this->error('系统繁忙');
        }
        //Step1:检查时间
        $startTime = strtotime($allGame['all_b_time']);
        $endTime = strtotime($allGame['all_e_time']);
        $timeNow = time();
        $canBaoStatus = 0;
        if ($startTime < $timeNow && $endTime > $timeNow) {
            $canBaoStatus = 1;
        }
        if ($canBaoStatus != 1) {
            $this->error("对不起,报名时间为:{$allGame['all_b_time']} 到 {$allGame['all_e_time']}");
        }
        //Step2:查询人数范围
        $userGroupAuth = M('tb_project_auth')->where(array('id' => $game['auth_id']))->find();
        if (!$userGroupAuth) {
            $this->error('对不起,未配置组别范围');
        }
        //Step3:判断是个人还是机构
        if ($this->user['u_type'] == 1) {
            //检测自己的性别
            if ($game['g_sex'] != 0 && $game['g_sex'] != $this->user['sex']) {
                $this->error('对不起,您得性别不符合参赛要求');
            }
            $this->assign('user_json', json_encode($this->user));
        } else {
            //机构
            $this->assign('user_json', json_encode(array()));
        }
        //Step4:检测是否已经报名了


        //Step5:验证项目是否限制总人数
        if ($game['g_maxperson'] <= $game['current_count']) {
            $this->error('对不起,比赛人数已经饱和，请联系管理员调整');
        }

        //Step6:查看自己是否已经别人帮我报名了
        $gameJonExist = M('jon_game_logs')->where(array('user_id' => $this->user['u_id'], 'game_id' => $id))->find();
        if ($gameJonExist) {
            $this->error('对不起,您已经报过名,或者机构已经替您报名了');
        }
        //如果是个人用户

        if (IS_POST) {
            $uids = I('u_uid');
            //去check用户信息
            $checkAuthUsers = array();
            foreach ($uids as $k => $v) {
                $um = array();
                $um['u_id'] = $v;
                $authUserTmp = M('user')->where($um)->find();
                if (!$authUserTmp) {
                    $this->error('对不起,您添加的某个用户不存在,请重新尝试');
                }
                $checkAuthUsers[] = $authUserTmp;
                //这里还得验证一次性别 TODO


                //验证用户年龄 TODO


                //如果是
                $checkMap = array();
                $checkMap['game_id'] = $id;
                $checkMap['user_id'] = $authUserTmp['u_id'];
                $checkRet = M('jon_game_logs')->where($checkMap)->find();
                if ($checkRet) {
                    $this->error("对不起,当中有用户已经报过名了,请检查，UID:{$authUserTmp['u_id']}");
                }
            }
            $nowJoinCount = count($checkAuthUsers);
            if ($userGroupAuth['min_count'] > $nowJoinCount) {
                $this->error("报名人数必须大于等于:{$userGroupAuth['min_count']}人次");
            }
            //
            if ($userGroupAuth['max_count'] < $nowJoinCount) {
                $this->error("报名人数必须小于等于:{$userGroupAuth['min_count']}人次");
            }

            $data['u_id'] = $this->user['u_id'];
            $data['wb_ids'] = json_encode($uids);
            $data['g_id'] = $id;
            $data['g_date'] = date('Y-m-d H:i:s');
            $data['j_status'] = 0;

            //计算项目费用
            $data['pay_money'] = $game['g_money'] * $nowJoinCount;
            $data['create_time'] = time();
            $data['pay_status'] = 0;
            $data['order_no'] = OrderHelper::createOrderNo();
            M()->startTrans();//开启
            $addRet = M('jon_game')->add($data);
            //增加统计
            $upGameCountRet = M('game')->where(array('g_id' => $id))->setInc('current_count', $nowJoinCount);
            //增加会员消费
            M('user')->where(array('u_id' => $this->user['u_id']))->setInc('total_project_count');
            //循环写入日志
            foreach ($uids as $k => $v) {
                $uAddLog = array();
                $uAddLog['game_id'] = $id;
                $uAddLog['jg_id'] = $this->user['u_id'];
                $uAddLog['time'] = time();
                $uAddLog['user_id'] = $v;
                $uAddLog['jon_id'] = $addRet;
                $uAddLogRet = M('jon_game_logs')->add($uAddLog);
            }
            if ($addRet && $upGameCountRet) {
                //添加成功后
                //增加统计
                M()->commit();
                $this->success('报名成功', U('project/detail?j_id=' . $addRet));
            } else {
                M()->rollback();
                $this->error('报名失败' . M('game')->getError());
            }
        } else {
            $this->assign('group_auth', $userGroupAuth);
            $this->assign('_game', $game);
            $this->assign('_all_game', $allGame);
            $this->display();
        }
    }

    public function detail()
    {
        $map = array();
        $map['jon_game.j_id'] = I('j_id');
        $project = M('jon_game')->join('LEFT JOIN game ON game.g_id=jon_game.g_id')
            ->join('LEFT JOIN user ON user.u_id=jon_game.u_id')
            ->where($map)
            ->find();

        //拿舞信息
        if (!$project) {
            $this->error('系统错误');
        }
        $wbIds = json_decode($project['wb_ids'], true);
        $wbIdsReal = array();
        foreach ($wbIds as $k => $v) {
            $wbIdsReal[] = $v;
        }

        $wbs = M('user')->where(array('u_id' => array('in', $wbIdsReal)))->select();

        $this->assign('_wbList', $wbs);
        $this->assign('_project', $project);
        $this->display();
    }
}